package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 获得营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnOverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();

        datelist.add(begin);

        while(!begin.equals(end)){
        begin = begin.plusDays(1);
        datelist.add(begin);
        }

        List<Double> trunOverList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //select sum(amount) from orders where order_time > beginTime and order_time < endTime and status = 5
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double trunOver = orderMapper.sumByMap(map);
            trunOver = trunOver == null ? 0.0 :trunOver;
            trunOverList.add(trunOver);
        }
       return TurnoverReportVO.builder()
               .dateList(StringUtils.join(datelist,","))
               .turnoverList(StringUtils.join(trunOverList,","))
               .build();
    }

    /**
     * 统计动态时间端内用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();

        datelist.add(begin);

        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //select count(id) from user where order_time > beginTime and order_time < endTime
            //select count(id) from user where order_time >beginTime
            Map map = new HashMap<>();
            map.put("end",endTime);

            Integer totalUser = userMapper.countByMap(map);
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);

            newUser = newUser == null ? 0 : newUser;
            totalUser = totalUser == null ? 0 :totalUser;

            newUserList.add(newUser);
            totalUserList.add(totalUser);


        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();

    }

    /**
     * 统计动态时间端内订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        if (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> countOrderList = new ArrayList<>();
        List<Integer> validCountOrderList = new ArrayList<>();

        Double orderCompletionRate;
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer countOrder = orderMapper.countByMap(map);

            map.put("status", Orders.COMPLETED);
            Integer validCountOrder = orderMapper.countByMap(map);

            countOrder = countOrder == null ? 0 : countOrder;
            validCountOrder = validCountOrder == null ? 0 : validCountOrder;

            countOrderList.add(countOrder);
            validCountOrderList.add(validCountOrder);

            totalOrderCount = countOrderList.stream().reduce(Integer::sum).get();
            validOrderCount = validCountOrderList.stream().reduce(Integer::sum).get();

        }

        orderCompletionRate = (totalOrderCount == 0) ? 0.0 :
                (double) validOrderCount / totalOrderCount;


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(countOrderList, ","))
                .validOrderCountList(StringUtils.join(validCountOrderList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }


    /**
     * 统计动态时间端内销量top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> name = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> number =salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        String nameList = StringUtils.join(name, ",");
        String numberList = StringUtils.join(number, ",");


        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 数据报表导出
     * @param response
     */
    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        //查询数据库获取营业的数据
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);


        //通过 poi 将数据写入到 Excel 文件中
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(endTime, LocalTime.MAX));

        try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
             XSSFWorkbook excel = new XSSFWorkbook(in);
             ServletOutputStream outputStream = response.getOutputStream()) {

            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue("报表时间：" + beginTime + "到" + endTime);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate dateTime = beginTime.plusDays(i);

                BusinessDataVO businessData = workspaceService.getBusinessData(
                        LocalDateTime.of(dateTime, LocalTime.MIN),
                        LocalDateTime.of(dateTime, LocalTime.MAX)
                );

                row = sheet.getRow(7 + i);
                if (row == null) {
                    row = sheet.createRow(7 + i);
                }

                row.createCell(1).setCellValue(dateTime.toString());
                row.createCell(2).setCellValue(businessData.getTurnover());
                row.createCell(3).setCellValue(businessData.getValidOrderCount());
                row.createCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.createCell(5).setCellValue(businessData.getUnitPrice());
                row.createCell(6).setCellValue(businessData.getNewUsers());
            }

            excel.write(outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
